<template>
  <div>
    <template>
      <van-form @submit="onSubmit">
        <van-field
          type="password"
          name="oldPassword"
          v-model="oldPassword"
          label="旧密码"
          placeholder="旧密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
        <van-cell-group>
          <van-field
            type="password"
            name="newPassword"
            v-model="newPassword"
            label="新密码"
            placeholder="新密码"
            :rules="[{ validator: pswValidator, message: '密码至少为6位数' }]"
          />
          <van-field
            type="password"
            name="confirmPassword"
            v-model="confirmPassword"
            label="确认密码"
            placeholder="确认密码"
            :rules="[{ validator: validator, message: '密码不一致' }]"
          />
        </van-cell-group>
        <div class="btn">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
        <!-- <div class="btn" v-if="$checkRole() === 1">
          <van-button
            round
            block
            type="danger"
            native-type="button"
            @click="openDialog"
          >
            重置密码
          </van-button>
        </div> -->
      </van-form>
    </template>
  </div>
</template>

<script>
import { update,reset } from "@/api/psw";
import { Toast } from "vant";
import { Dialog } from "vant";
export default {
  data() {
    return {
      oldPassword: "",
      newPassword: "",
      confirmPassword: "",
    };
  },
  methods: {
    async onSubmit(values) {
      let params = {
        newPassword: this.newPassword,
        oldPassword: this.oldPassword,
      };
      if (!this.$_.isEmpty(params)) {
        let res = await update(params);
        if (res.code === 1) {
          Toast("密码修改成功，需重新登录！");
          setTimeout(() => {
            this.$router.replace("/login");
          }, 2000);
        }
      }
    },
    validator(val) {
      if (val !== this.newPassword) {
        return false;
      }
    },
    pswValidator(val){
        if (val.length<6) {
        return false;
      }
    },
    async openDialog() {
        let _this=this
      Dialog.confirm({
        title: "重置密码",
        message: "密码重置为123456，是否确认操作？",
      })
        .then(async () => {
          // on confirm
          let res=await reset({id:1})
          if(res.code===1){
              Toast('重置密码成功，请重新登录！')
              setTimeout(()=>{
                  _this.$router.push('/login')
              },2000)
          }
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.btn {
  width: 90%;
  margin: 20px auto 0;
}
</style>